package service;

import java.util.Stack;

/**
 * Created by fanzhenyu02 on 2020/8/10.
 */
public class ParaScore {


    // travel through every sigle character in s
    // when "(", pop into stack
    // when ")" we need to loo up in stack:
    // 1. stack top character is:'(' then the total score,add 2 ^(n-1, n equals to stack depth.)
    // 2. stack top character is:')' dirct pop the character

    public int calculateScore(String s) {
        int score = 0;
        int length = s.length();
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < length; ++i) {
            char temp = s.charAt(i);
            if (temp == '(') stack.add(temp);
            else {//((()))
                if (s.charAt(i - 1) == '(') {  // ((9)()()()()()()))
                    score += Math.pow(2, stack.size() - 1);  //score = 2 +2^2=6
                    stack.pop(); // elemimiate last "(".
                } else {
                    // last is ")".
                    stack.pop();
                }
            }
        }

        return score;
    }

    public static void main(String[] args) {
        ParaScore ps = new ParaScore();
        System.out.println(ps.calculateScore("()()"));
    }

}
